<template>
	<view class="client-container">
		<!-- 顶部搜索区域 -->
		<view class="search-area">
			<view class="search-box">
				<u-icon name="search" size="28" color="#909399"></u-icon>
				<input type="text" placeholder="输入人名/电话/微信/拼音/手机号" v-model="searchKeyword" @confirm="loadClientData" />
			</view>
			<view class="search-actions">
				<text class="search-btn" @click="loadClientData">搜索</text>
				<text class="only-arrears" :class="{'active': onlyArrears}" @click="toggleOnlyArrears">只看欠款</text>
			</view>
		</view>
		
		<!-- 筛选条件标签显示区域 -->
		<view class="filter-tags" v-if="searchKeyword">
			<scroll-view scroll-x class="filter-tags-scroll">
				<view class="filter-tag">
					关键词: {{searchKeyword}}
					<text class="tag-close" @click="clearSearch">×</text>
				</view>
			</scroll-view>
		</view>
		
		<!-- 客户列表区域 -->
		<view class="client-list" v-if="clientList.length > 0">
			<view class="client-item" v-for="(item, index) in clientList" :key="item.id">
				<view class="client-info" @click="viewClientDetail(item)">
					<view class="client-name">{{ item.customerName || '未命名客户' }}</view>
					<view class="client-meta">
						<text class="client-category" v-if="item.categoryName">{{item.categoryName}}</text>
						<text class="client-phone">{{ item.contactPhone || item.contactPhone || '无联系方式' }}</text>
					</view>
				</view>
				<view class="client-amount" :class="{'amount-positive': item.amount >= 0, 'amount-negative': item.amount < 0}">
					<text>{{ item.amount >= 0 ? '余额' : '欠款' }}</text>
					<text class="amount">{{ Math.abs(Number(item.amount) || 0).toFixed(2) }}</text>
				</view>
				<view class="client-actions">
					<view class="action-btn edit" @click="editClient(item)">
						<u-icon name="edit-pen" color="#2979ff" size="20"></u-icon>
					</view>
					<view class="action-btn delete" @click="confirmDeleteClient(item)">
						<u-icon name="trash" color="#fa3534" size="20"></u-icon>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<u-loadmore :status="loadStatus" @loadmore="loadMore"></u-loadmore>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<image src="/static/images/empty-client.png" class="empty-image" mode="aspectFit"></image>
			<text class="empty-text">{{ searchKeyword ? '未搜索到相关客户' : '暂无客户管理信息' }}</text>
			<view class="empty-tips" v-if="searchKeyword">
				<text @click="clearSearch">清除筛选条件</text>
			</view>
		</view>
		
		<!-- 底部新增按钮 -->
		<view class="add-client-btn" @click="addNewClient">
			<u-icon name="plus" color="#fff" size="24"></u-icon>
			<text>新增客户</text>
		</view>
		
		<!-- 删除确认弹窗 -->
		<u-modal v-model="deleteModalVisible" content="确定要删除该客户吗？此操作不可恢复。" :show-cancel-button="true" @confirm="deleteClient"></u-modal>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	
	export default {
		data() {
			return {
				searchKeyword: '',
				onlyArrears: false,
				clientList: [],
				page: 1,
				pageSize: 10,
				total: 0,
				hasMore: false,
				loadStatus: 'loadmore', // loadmore, loading, nomore
				deleteModalVisible: false,
				currentDeleteItem: null, // 当前要删除的客户对象
			}
		},
		onShow() {
			// 加载客户数据
			this.loadClientData();
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.refreshData();
		},
		methods: {
			// 刷新数据
			refreshData() {
				this.page = 1;
				this.loadClientData().then(() => {
					uni.stopPullDownRefresh();
				}).catch(() => {
					uni.stopPullDownRefresh();
				});
			},
			
			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
				this.loadClientData();
			},
			
			// 加载客户数据
			loadClientData(isLoadMore = false) {
				return new Promise((resolve, reject) => {
					if (!isLoadMore) {
						this.page = 1;
						this.clientList = [];
					}
					
					uni.showLoading({
						title: '加载中...'
					});
					
					const params = {
						pageNum: this.page,
						pageSize: this.pageSize
					};
					
					// 添加关键词搜索条件
					if (this.searchKeyword) {
						params.keyword = this.searchKeyword;
					}
					
					// 添加只看欠款筛选条件
					if (this.onlyArrears) {
						params.onlyArrears = true;
					}
					
					console.log('搜索参数:', params);
					
					api.listCustomer(params).then(res => {
						console.log('客户列表返回:', res);
						uni.hideLoading();
						
						if (res && res.rows) {
							if (isLoadMore) {
								this.clientList = [...this.clientList, ...res.rows];
							} else {
								this.clientList = res.rows;
							}
							this.total = res.total;
							
							// 是否还有更多数据
							if (this.clientList.length >= this.total) {
								this.hasMore = false;
								this.loadStatus = 'nomore';
							} else {
								this.hasMore = true;
								this.loadStatus = 'loadmore';
							}
						} else {
							if (!isLoadMore) {
								this.clientList = [];
							}
							this.hasMore = false;
							this.loadStatus = 'nomore';
						}
						
						resolve();
					}).catch(err => {
						console.error('客户列表请求失败:', err);
						uni.hideLoading();
						uni.showToast({ 
							title: '加载失败', 
							icon: 'none' 
						});
						this.loadStatus = 'loadmore';
						
						reject(err);
					});
				});
			},
			
			// 加载更多
			loadMore() {
				if (this.loadStatus !== 'loadmore') return;
				this.page++;
				this.loadStatus = 'loading';
				this.loadClientData(true);
			},
			
			// 切换是否只显示欠款客户
			toggleOnlyArrears() {
				this.onlyArrears = !this.onlyArrears;
				uni.showToast({
					title: this.onlyArrears ? '已切换到只看欠款' : '已显示全部客户',
					icon: 'none'
				});
				this.loadClientData(); // 重新加载数据
			},
			
			// 查看客户详情
			viewClientDetail(client) {
				uni.navigateTo({
					url: `/subPack/client/add?id=${client.id}`
				});
			},
			
			// 编辑客户
			editClient(client) {
				uni.navigateTo({
					url: `/subPack/client/add?id=${client.id}`
				});
			},
			
			// 确认删除客户
			confirmDeleteClient(client) {
				this.currentDeleteItem = client;
				this.deleteModalVisible = true;
			},
			
			// 删除客户
			deleteClient() {
				if (!this.currentDeleteItem || !this.currentDeleteItem.id) {
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '删除中...'
				});
				
				api.deleteCustomer(this.currentDeleteItem.id).then(res => {
					uni.hideLoading();
					if (res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						// 重新加载数据
						this.loadClientData();
					} else {
						uni.showToast({
							title: res.msg || '删除失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('删除客户失败:', err);
					uni.hideLoading();
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					});
				});
				
				this.currentDeleteItem = null;
			},
			
			// 新增客户
			addNewClient() {
				uni.navigateTo({
					url: '/subPack/client/add'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.client-container {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding-bottom: 120rpx; /* 为底部按钮留出空间 */
}

/* 搜索区域样式 */
.search-area {
	padding: 20rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	border-bottom: 1px solid #eee;
	
	.search-box {
		flex: 1;
		height: 72rpx;
		background-color: #f5f5f5;
		border-radius: 36rpx;
		padding: 0 24rpx;
		display: flex;
		align-items: center;
		
		input {
			flex: 1;
			height: 100%;
			margin-left: 12rpx;
			font-size: 28rpx;
		}
	}
	
	.search-actions {
		display: flex;
		align-items: center;
		
		.search-btn {
			margin-left: 20rpx;
			padding: 0 20rpx;
			height: 72rpx;
			line-height: 72rpx;
			color: #2979ff;
			font-size: 28rpx;
		}
		
		.only-arrears {
			font-size: 26rpx;
			color: #2979ff;
			margin-left: 20rpx;
			padding: 0 10rpx;
			
			&.active {
				color: #fa3534;
				font-weight: bold;
			}
		}
	}
}

/* 筛选标签样式 */
.filter-tags {
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	
	.filter-tags-scroll {
		display: flex;
		white-space: nowrap;
		
		.filter-tag {
			display: inline-block;
			background-color: #f2f6fc;
			color: #2979ff;
			padding: 8rpx 24rpx;
			border-radius: 30rpx;
			font-size: 24rpx;
			margin-right: 16rpx;
			
			.tag-close {
				margin-left: 8rpx;
				color: #909399;
			}
		}
	}
}

/* 客户列表样式 */
.client-list {
	background-color: #fff;
	
	.client-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 20rpx;
		border-bottom: 1px solid #eee;
		position: relative;
		
		.client-info {
			flex: 1;
			
			.client-name {
				font-size: 30rpx;
				color: #333;
				margin-bottom: 6rpx;
				font-weight: 500;
			}
			
			.client-meta {
				display: flex;
				align-items: center;
				
				.client-category {
					font-size: 22rpx;
					color: #fff;
					background-color: #2979ff;
					padding: 2rpx 12rpx;
					border-radius: 20rpx;
					margin-right: 12rpx;
				}
				
				.client-phone {
					font-size: 24rpx;
					color: #909399;
				}
			}
		}
		
		.client-amount {
			text-align: right;
			margin-right: 20rpx;
			
			text {
				font-size: 24rpx;
				color: #909399;
				display: block;
			}
			
			.amount {
				font-size: 30rpx;
				font-weight: 500;
				margin-top: 4rpx;
			}
			
			&.amount-positive {
				.amount {
					color: #19be6b;
				}
			}
			
			&.amount-negative {
				.amount {
					color: #fa3534;
				}
			}
		}
		
		.client-actions {
			display: flex;
			align-items: center;
			
			.action-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				
				&.edit {
					margin-right: 10rpx;
				}
			}
		}
	}
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #909399;
	}
	
	.empty-tips {
		margin-top: 20rpx;
		
		text {
			font-size: 26rpx;
			color: #2979ff;
		}
	}
}

/* 加载更多 */
.load-more {
	padding: 20rpx 0;
	text-align: center;
}

/* 底部新增按钮 */
.add-client-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #2979ff;
	color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	font-weight: 500;
	
	text {
		margin-left: 8rpx;
	}
}
</style> 